<?php

namespace App\Http\Controllers\Front;

use App\Interfaces\CartService;
use App\Models\UserSocialite;
use Illuminate\Http\Request;

use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Redirect;
use App\Http\Requests\Front\UserLoginRequest;
use App\Http\Requests\Front\UserRegisterRequest;
use App\Http\Requests\Front\TellRequest;
use Gregwar\Captcha\CaptchaBuilder;
use App\Models\User;
use App\Models\MessageCode;
use Overtrue\Socialite\InvalidArgumentException;
use Session,Auth,Validator,Input,Log;
use Illuminate\Support\Facades\Mail;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Interfaces\SmsService;
use App\Interfaces\UserService;
use App\Exceptions\Interfaces\UserServiceException;
use Overtrue\Socialite\SocialiteManager;
class UserController extends Controller
{


    public function login(Request $request){

        $returnUrl = $request->get('return_url');

        return view('front.user.login',compact('returnUrl'));
    }
    public function socialiteLogin($name){

        $config[$name]=Config::get('socialite.'.$name);

        if(empty($config[$name])){
            abort(404);
        }
        $socialite = new SocialiteManager($config);

        $response = $socialite->driver($name)->redirect();
        $response->send();
    }
    public function socialiteCallback(Request $request,CartService $cartService,$name){
        $config[$name]=Config::get('socialite.'.$name);
        $socialite = new SocialiteManager($config);
        $user=$socialite->driver($name)->user();
        //判断是否注册
        $userSocialite= UserSocialite::where('socialite_type','=',$name)->where('socialite_id','=',$user->getId())->first();
        if(!$userSocialite){//未注册 执行注册流程
            $userRegister=new User();
            $userRegister->user_name=$user->getNickname();
            $userRegister->is_disabled = 0;
            $userRegister->save();
            $userSocialite=new UserSocialite();
            $userSocialite->user_id=$userRegister->id;
            $userSocialite->socialite_id=$user->getId();
            $userSocialite->socialite_type=$name;
            $userSocialite->save();
        }
        $userRegister=User::find($userSocialite->user_id);
        //执行登陆流程
        Auth::login($userRegister,true);
        if(Auth::check()){
            $userRegister->last_login_ip = $request->ip();
            $userRegister->last_login_time = date('Y-m-d H:i:s',time());
            $userRegister->save();
        }
        //关联购物车商品
        $cartService->linkSessionToUser($request->get('session_id'),$userRegister->id);
        return redirect('/');
    }

    public function loginOk(Request $userLoginRequest,CartService $cartService){


        $returnUrl = $userLoginRequest->get('return_url');

        //TODO  验证码


        if(User::where('email',trim(Input::get('user_name')))->first()){
            $user = User::where('email',trim(Input::get('user_name')))->first();
        }elseif(User::where('phone',trim(Input::get('user_name')))->first()){
            $user = User::where('phone',trim(Input::get('user_name')))->first();
        }elseif(User::where('user_name',trim(Input::get('user_name')))->first()){
            $user = User::where('user_name',trim(Input::get('user_name')))->first();
        }else{
            return redirect()->back()->withInput()->withErrors('用户不存在');
        }
        $remember = Input::get('rememberMe');

        $password = $userLoginRequest->get('password');
            if ($password!=''&&md5($password)===$user->password){
                if($user->is_disabled==0){
                    if ($remember){
                        Auth::login($user,true);
                    }else{
                        Auth::login($user,false);
                    }

                    if(Auth::check()){

                        $user->last_login_ip = $userLoginRequest->ip();
                        $user->last_login_time = date('Y-m-d H:i:s',time());
                        $user->save();
                    }

                    //关联购物车商品
                    $cartService->linkSessionToUser($userLoginRequest->get('session_id'),$user->id);


                    if ($returnUrl){
                        return redirect($returnUrl);
                    }else{
                        return redirect('/');
                    }

                }else{
                    return redirect()->back()->withInput()->withErrors('用户被禁止登录');

                }

            }else{
                return redirect()->back()->withInput()->withErrors('用户名或密码错误');

            }


    }


    public function logout(Request $request){

        $returnUrl = $request->get('returnUrl');
        if(Auth::check()){

            Auth::logout();
        }


        if ($returnUrl){
            return redirect($returnUrl);
        }else{
            return redirect('/');
        }


    }

    public function register(){
        return view('front.user.register');
    }

    public function checkUser(Request $request){
        $user_name = $request->get("user_name");
        $user = User::where('user_name',$user_name)->get()->toArray();
        if($user){
            return response()->json(false);
        }else{
            return response()->json(true);
        }
    }

    public function registerOk(UserRegisterRequest $userRegisterRequest,SmsService $sms,UserService $userService){

        $user_name = Input::get('user_name');

        if(!ctype_alnum($user_name)){
            return response()->json(['status'=>0,'message'=>'用户名必须是字母或数字，或者字母和数字组合']);
        }
        $password = Input::get('password');

        $phone = Input::get('phone');

        //$chkCode = Input::get('chkCode');

        $mesCode = Input::get('MsgCode');

        $agreement = Input::get('agreement');

        $message_id = Session::get('MsgCode_id');

        $is_username = User::where('user_name',trim($user_name))->first();

        $is_phone = User::where('phone',trim($phone))->first();

        $validateRegCode = $sms->validateRegCode($message_id,$mesCode);


        if($agreement){
            if($validateRegCode){
                if($phone != MessageCode::find($message_id)->phone){
                    return response()->json(['status'=>0,'message'=>'两次输入的手机号不一样，请重新获取验证码']);
                }
                $rules = $userRegisterRequest->rules();
                $messages = $userRegisterRequest->messages();

                $validator = Validator::make(Input::all(),$rules,$messages);
                //验证通过 是否同意章程 图片验证码一致  验证码是否一致
                if($validator->passes()){
                    if($is_username){

                        return response()->json(['status'=>0,'message'=>'该用户名已被使用注册！']);
                    }
                    if($is_phone){
                        return response()->json(['status'=>0,'message'=>'该手机号已验证！']);

                    }

                    $register = $userService->reg($user_name,$password,$phone);

                    if($register){

                        $register->device=2;
                        $register->save();

                        $messageCode = MessageCode::find(Session::get('MsgCode_id'));

                        $messageCode->delete();

                        return view('front.user.regsuccess');
                    }else{
                        return response()->json(['status'=>0,'message'=>'注册失败！']);

                    }

                }else{

                    return response()->json(['status'=>0,'message'=>'请正确填写下列数据！']);
                }


            }else{
                return response()->json(['status'=>0,'message'=>'短信验证码已失效，请重新获取！']);
            }


        }else{
            return response()->json(['status'=>0,'message'=>'是否同意该章程！']);
        }

    }

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function captcha($tmp,CaptchaBuilder $builder)
    {
        //图片效果设置样放在 build 方法前面
        $builder->setMaxBehindLines(2);                 //背景干扰线
        $builder->setMaxFrontLines(0);                  //前置干扰线
        $builder->setMaxOffset(6);                      //设置偏移值
        $builder->setDistortion(false);                //是否失真
        //$builder->setBackgroundImages();                //设置背景图片
        //$builder->setInterpolation(false);              //Enable/Disables the interpolation
        //$builder->setMaxAngle();                        //最大倾斜角度
        //$builder->setBackgroundColor(96,96,96);         //背景色
        //$builder->setTextColor(255,255,255);            //文字颜色
        //$builder->setIgnoreAllEffects(true);            //是否禁用所有干扰（干扰线、失真）
        //$builder->setPhrase('123456');                  //设置验证码的值

        //可以设置图片宽高及字体
        $builder->build($width = 100, $height = 38, $font = null);

        //获取验证码的内容
        $phrase = $builder->getPhrase();

        //把内容存入session
        Session::put('milkcaptcha', $phrase);

        //生成图片
        header("Cache-Control: no-cache, must-revalidate");
        header('Content-Type: image/jpeg');
        $builder->output();
        $builder->inline();
    }


    public function sms(SmsService $sms,Request $request)
    {
        $sendLiveTime=60;
        $phone = $request->phone;
        $is_exit = User::where('phone', $phone)->first();
        $sendTime = MessageCode::where('phone',$phone)->orderBy('send_time','desc')->pluck('send_time');
        $chkCode = $request->get('chkCode');
        if($is_exit){
            return response()->json(['status'=>0,'message'=>'该手机号已验证！']);
        }
        if($chkCode!=Session::get('milkcaptcha')){
            return response()->json(['status'=>0,'message'=>'验证码错误！']);
        }

        if($sendTime){
            if(strtotime(date('Y-m-d H:i:s',time()))-strtotime($sendTime)>=$sendLiveTime){

                $message_id =  $sms->sendRegMsg($phone);
            }
        }else{
            $message_id =  $sms->sendRegMsg($phone);
        }

        if($message_id){
            Session::put('MsgCode_id',$message_id);
            Session::save();
            return response()->json(['status'=>1,'message'=>'发送成功！']);
        }else{
            return response()->json(['status'=>0,'message'=>'发送失败！']);
        }


    }

    /**
     * 发送邮件给用户
     *
     * @param  Request  $request
     * @param  int  $id
     * @return Response
     */
    public function sendEmail(Request $request)
    {
        //dd(Config::get('mail'));

        $id = $request->get('user_id');
        $email = $request->get('email');
        $is_email = User::where('email',$email)->first();
        if($is_email){
            return response()->json(['status'=>0,'message'=>'该邮箱已验证！']);
        }
        $user = User::findOrFail($id);

        //生成随机字符串
        $str='1234567890';
        $randStr = str_shuffle($str);//打乱字符串
        $code= substr($randStr,0,4);//substr(string,start,length);

        $data = ['email'=>$email,'name'=>$user->user_name,'user_id'=>$user->id,'code'=>$code];
        $result = Mail::send('front.user.activemail',$data, function ($message) use ($data) {
            $message->to($data['email'])->subject('欢迎注册我们的网站，请激活您的账号！');
        });
        if($result){
            $user->code = $code;
            $user->check_type=1;
            $user->send_time=date('Y-m-d H:i:s',time());
            $user->save();
            return response()->json(['status'=>$result]);
        }else{
            return response()->json(['status'=>$result,'message'=>'发送失败！']);
        }
    }


    /**
     * 查询用户是否实名认证
     * @param [number] $user_id [用户id]
     */
    public function hasIdVerity(UserService $userService){

        $user_id = Auth::user()->id;

        return $userService->hasIdVerity($user_id);
    }


    /**
     * 增加用户实名信息
     * @param [number] $user_id [用户id]
     * @param [string] $real_name [用户真实姓名]
     * @param [number] $id_type   [证件类型，1：身份证]
     * @param [string] $id_num    [证件号]
     */
    public function addIdVerity(Request $request, UserService $userService){

        $return = ['status'=>1, 'message'=>'增加用户实名信息成功', 'data'=>''];

        $user_id = Auth::user()->id();

        try {

            $userService->addIdVerity($user_id, $request->real_name, $request->id_type, $request->id_num);

        } catch (UserServiceException $e) {

            $return['status'] = 0;

            $return['message'] = $e->getMessage();

            return $return;
        }

        return $return;
    }



}
